package com.wxg.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.wxg.common.core.module.user.dao.mysql.User;
import com.wxg.user.service.UserCacheService;
import com.wxg.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author: Administrator
 * @date: 2022/12/19 14:21
 * @desc:
 */
@Slf4j
@Service
public class UserCacheServiceImpl implements UserCacheService {

    @Autowired
    private UserService userService;

    private LoadingCache<Long, String> USER_CACHE = null;

    /**
     * 启动时设置好类加载器，查询逻辑，当从USER_CACHE中获取数据时不存在则会查询db，并放入缓存中
     */
    @PostConstruct
    private void init(){
        USER_CACHE = CacheBuilder.newBuilder().refreshAfterWrite(20L, TimeUnit.SECONDS).build(
                new CacheLoader<Long, String>() {
                    /**
                     * 返回空时guava会报错，设置空字符串，由业务调用来决定处理方式
                     * @param userId
                     * @return
                     * @throws Exception
                     */
                    @Override
                    public String load(Long userId) throws Exception {
                        log.info("用户id:{}", userId);
                        User user = userService.queryById(userId);
                        log.info("用户信息:{}", JSON.toJSONString(user));
                        return user!=null ? user.getUserName() : "";
                    }
                }
        );
    }

    @Override
    public String queryUserWithCache(Long userId) {
        String userName = null;
        try {
            userName = USER_CACHE.get(userId);
        } catch (ExecutionException e) {
            log.error("查询用户异常", e);
        }
        return userName;
    }
}
